<template>
  <div class="container">
      <div v-if="!isNoData">
    <form action="/">
    <van-search v-model="searchWord" background="#f2f2f2"  placeholder="请输入搜索关键词"  @search="onSearch"
                @clear="onCancel"/>
    </form>
    </div>
    <div class="main pb1_3">

      <div v-for="item in courseList" class="video-item">
        <router-link :to="{path:'/video',query: {id: item.id}}">
        <div class="video-thumb-wrapper">
          <img src="http://218.22.139.29:5555/public/static/img/mock.jpg" />
          <span class="video-creattime">{{item.createtime | timeFormat('yyyy-mm-dd')}}</span>
          <span class="seen">已看{{item.jd}}</span>
          <van-icon name="play-circle-o" size="32" color="#fff" />
        </div>
        <div class="video-text">{{item.kcname}}</div>
        </router-link>
      </div>
      <div v-if="isNoData" class="nodata">--- 暂无数据 ---</div>
    </div>
    <Footer></Footer>

    <van-dialog v-model="showModel" title="信息选择" :beforeClose="beforeClose">
      <van-field
        readonly
        clickable
        name="category"
        :value="valueCategory"
        label="单位类别"
        placeholder="点击选择类别"
        @click="showPickerCategory = true"
      />
      <van-field
        readonly
        clickable
        name="units"
        :value="valueUnits"
        label="单位名称"
        placeholder="点击选择单位"
        @click="userinfo.kcdx ? showPickerUnits = true : showPickerUnits = false"
      />
    </van-dialog>

    <van-popup v-model="showPickerCategory" position="bottom">
      <van-picker
        show-toolbar
        :columns="columnsCategory"
        @confirm="onConfirmCategory"
        @cancel="showPickerCategory = false"
      />
    </van-popup>

    <van-popup v-model="showPickerUnits" position="bottom">
      <van-picker
        show-toolbar
        :columns="columnsUnits"
        @confirm="onConfirmUnits"
        @cancel="showPickerUnits = false"
      />
    </van-popup>

    <van-overlay :show="showOverlay" @click="showOverlay = true">
      <div class="overlay-wrapper">
        <div class="overlay-text">请等待管理员审核</div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
  import util from '@/common/util';
export default {
  data() {
    return {
      userinfo: {
        "id": '',//学员id
        "idcard": "",//学员身份证
        "stname": "",//学员姓名
        "sex": "",//学员性别
        "pic": "",//学员图片
        "danwei": "",//学员单位id
        "kcdx": "",//学员单位类别值
        "xueli": null,//学员学历
        "pwd": null,//学员登录密码（现在都为空）
        "telphone": '',//学员手机号码
        "zhuanye": null,//学员专业
        "isshenhe": '',//审核情况
        "isstatus": '',//状态
        "createtime": ""//创建时间
      },
      isNoData: true,
      courseList:[],
      searchWord: '',
      showOverlay: false,
      showModel: false,
      valueCategory: '',
      showPickerCategory: false,
      columnsCategory:[],
      valueUnits: '',
      showPickerUnits: false,
      columnsUnits: [],
    }
  },

  created() {
    let that = this;
    that.isHaveStorage(); // 调用缓存信息
    that.getCategory(); // 调用单位类别
    //that.getCourseList(); // 调用课程列表
  },

  methods: {
    onSearch(val) {  //搜索
      let that = this;
      that.$api.post('/mobile/Index/index',{'user':that.userinfo,'content':val}, r => {
        that.courseList = r.data.info;
      })
    },
    onCancel() {
      this.getCourseList()
    },
    isHaveStorage() {  // 判断是否有用户信息缓存，如果有就把缓存赋给userinfo
      let that  = this;
      console.log('是否有缓存：',!!util.storage.get('userinfo'));
      //alert(!!util.storage.get('userinfo'));  // 1调试代码
      if(util.storage.get('userinfo')){
        //console.log('有缓存')
        that.userinfo = util.storage.get('userinfo');
        that.getCourseList();  // 获取课程信息
        //console.log('第一次之后缓存中信息',that.userinfo)
        // console.log('有缓存时单位',that.userinfo.danwei)
        if(!that.userinfo.danwei){
          that.showModel = true;
        }
      } else {
        that.getToken(); //【正式环境】没有缓存，请求第三方获取userinfo存入缓存
       // util.storage.set('userinfo', that.userinfo); // 【开发环境】模拟存取用户信息缓存
      }
    },

    // 获取token
    getToken(){
      let that = this;
      var ua = navigator.userAgent.toLowerCase();
      if (typeof(util.storage.get('userinfo')) === 'undefined' || util.storage.get('userinfo') === null) {
        that.$toast.loading({
          message: '加载中...',
        });
       // alert('进入判断获取缓存'); //调试代码
        croods.customPlugin({
          action: "UserPlugin.login",
          params: {},
          success: function (res) {
            //console.log('UserPlugin.login', res.token);
            let token = res.token;
            //alert(JSON.stringify(res))
            // 75d27d50021c4cb7a7d69980c2936b9b
            // 17af0889f9d94e92a8b7360c352b2565
            // 获取用户信息
            that.$api.get('/mobile/Login/login?token=' + token, null, r => {
              //alert(JSON.stringify(r)); //调试代码
              that.userinfo = r.data;
              //console.log('r',r)
              that.getCourseList();  // 获取课程信息
              that.$toast.clear();
              util.storage.set('userinfo',r.data)
              //console.log('无缓存danwei',r.data.danwei);
              if(!r.data.kcdx){
                that.showModel = true;
              }
            })
          },
          fail: function (msg) {
            alert('获取token失败');
            fly.tooltip(msg);
            throw new Error('Calling croods interface [UserPlugin.login] fail');
          }
        });

        // that.$api.get('/mobile/Login/login?token=75d27d50021c4cb7a7d69980c2936b9b', null, r => {
        //   //alert(JSON.stringify(r)); //调试代码
        //   //console.log(r)
        //   that.userinfo = r.data;
        //   //console.log('r',r)
        //   that.getCourseList();  // 获取课程信息
        //   that.$toast.clear();
        //   util.storage.set('userinfo',r.data);
        //   console.log('无缓存danwei',r.data.kcdx);
        //   if(!r.data.kcdx){
        //     that.showModel = true;
        //   }
        // })

      }
    },

    // 获取单位类别
    getCategory() {
      let that = this;
      that.$api.post('/mobile/Login/get_dwleibie', null, r => {
        console.log('单位类别',r)
        let categoryColumns = [];
        r.data.forEach(function(item){
          let categoryObj = {
            'text': item.leibie,
            'lid': item.kcdx
          };
          categoryColumns.push(categoryObj)
        });
        that.columnsCategory = categoryColumns;
      })
    },

    // 获取单位名称
    getUnits() {
      let that = this;
      console.log('lib',that.userinfo.kcdx)
      that.$api.post('/mobile/Login/get_danwei',{'lid':that.userinfo.kcdx}, r => {
        console.log('单位名称',r)
        let untilsColumns = [];
        r.data.dwls.forEach(function(item){
          let untilsObj = {
            'text': item.ldname,
            'did': item['id']
          }
          untilsColumns.push(untilsObj)
        });
        that.columnsUnits = untilsColumns;
      })
    },

    onConfirmCategory(value, index) {
      //console.log('单位类别：',value)
      this.valueCategory = value['text'];
      this.userinfo.kcdx = value['lid'];
      this.getUnits(); //调用单位名称，选择单位类别后才能选择单位名称
      this.showPickerCategory = false;
    },

    onConfirmUnits(value) {
      this.valueUnits = value['text'];
      this.userinfo.danwei = value['did'];
      //this.did = value['did'];
      this.showPickerUnits = false;
      //console.log('userinfo',this.userinfo)
    },

    getCourseList() { //获取课程列表
      let that = this;
      console.log('获取课程that.userinfo',that.userinfo)
      that.$api.post('/mobile/Index/index', {'user':that.userinfo}, r => {
        console.log('课程信息',r)
        if(r.data.is_pay === 2){ // 判断是否支付
          that.showOverlay = true;
        } else {
          console.log('重新存入缓存',r.data.user)
          util.storage.set('userinfo',r.data.user);
        }
        that.courseList = r.data.info || []; //课程列表
        console.log('课程信息',that.courseList)
        console.log('有数据吗',that.courseList.length != 0);
        that.courseList.length != 0 ? that.isNoData = false : that.isNoData = true;
      })
    },

    // 点击弹窗确认事件
    beforeClose(action, done) {
      let that = this;
      if(!this.valueUnits) {
        this.$toast("请选择单位！")
        done(false) //不关闭弹框
      }
      //console.log('单位类别',that.userinfo.kcdx);
      //console.log('单位制',that.userinfo.danwei); return false;

      if(action === 'confirm' && !!this.valueUnits) {
        that.$api.post('/mobile/login/supplement',{'user':{'id':that.userinfo.id,'did': that.userinfo.danwei, 'lid': that.userinfo.kcdx}}, r => {
          console.log('保存单位',r)
          if(r.code == 1){
            util.storage.set('userinfo', that.userinfo);
            setTimeout(done, 500);
            that.showOverlay = true;
          } else{
            //that.$toast("保存失败！请稍后重试。")
            done(false)
          }
        })
      } else if(action === 'cancel') {
        done() //关闭
      }
    }
  }
}
</script>

<style>
  *{box-sizing: border-box;}
  body{
    margin: 0;
  }
  .overlay-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  .overlay-text {
    width: 60%;
    height: 80px;
    font-size: .32rem;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    border-radius: 5px;
  }
  .main {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 0 12px;
  }
  .video-item {
    width: 48%;
    margin-bottom: 12px;
  }
  .video-thumb-wrapper {
    position: relative;
  }
  .video-thumb-wrapper img {
    display: block;
    width: 100%;
  }
  .video-creattime {
    position: absolute;
    left: 10px;
    top: 10px;
    font-size: .24rem;
    color: #fff;
  }
  .seen {
    position: absolute;
    bottom: 10px;
    right: 10px;
    font-size: .24rem;
    color: #fff;
  }
  .video-text {
    line-height: 1.4;
    font-size: .28rem;
  }
  .van-search__content {
    height: 36px;
    background-color: #fff;
  }
  .van-icon-play-circle-o {
    position: absolute!important;
    top: 50%;
    left: 50%;
    margin-left: -16px;
    margin-top: -16px;
  }
</style>
